// Learn cc.Class:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const GameDataManger = require("../GameDataManger");
const UIPanelManager = require("../UIPanelManager");

cc.Class({
    extends: cc.Component,

    properties: {
        statauLab:{     
            default:null,
            type:cc.Label
        },

        timeLab:{     
            default:null,
            type:cc.Label
        },

        role1:{     
            default:null,
            type:cc.Node
        },

        role2:{     
            default:null,
            type:cc.Node
        },

        nameLab1:{     
            default:null,
            type:cc.Label
        },

        nameLab2:{     
            default:null,
            type:cc.Label
        },

        time:0,
    },

    onLoad(){
        cc.systemEvent.on('refreshMatch', this.refreshRole, this);
    },

    onEnable(){

        cc.systemEvent.emit('sendMessage', 1021, [1]);

        this.node.getChildByName("closeBtn").active = true;

        this.time = 3
        this.statauLab.string = "匹配中"
        this.timeLab.string = "";
        this.refreshRole();
    },

    refreshRole(){
        if (!this.node.active){
            return
        }
        this.nameLab1.string = "";
        this.nameLab2.string = "";
        this.role1.active = false;
        this.role2.active = false;

        let count = 0
        if (players[0] && players[0].status == 1){
            this.role1.active = true;
            this.nameLab1.string = players[0].name;
            this.role1.getComponent("head").refresh(0, true, players[0]);

            count++
        }

        if (players[1] && players[1].status == 1){
            this.role2.active = true;
            this.nameLab2.string = players[1].name;
            this.role2.getComponent("head").refresh(0, true, players[1]);

            count++
        }

        if (count >= 2 && this.node.getChildByName("closeBtn").active){
            this.statauLab.string = "匹配成功"
            this.time = 3
            this.timeLab.string = 3;
            this.node.getChildByName("closeBtn").active = false;
            this.schedule(this.updateTime, 1);
        }
    },

    updateTime(){
        this.time--;
        this.timeLab.string = this.time;
        if (this.time <= 0){
            this.unschedule(this.updateTime);

            GameDataManger.gameType = 1;
            var ranIndex = Math.floor(Math.random()*2); //先手，0红方，1绿方
            cc.systemEvent.emit('sendMessage', 1002, [ranIndex,false]);
            UIPanelManager.close(this.node)
            UIPanelManager.close(UIPanelManager.gradeNode)
        }
    },

    onDisable(){
        cc.systemEvent.emit('sendMessage', 1021, [0]);
    },

    // update (dt) {},
});
